<template>
  <div class="page">
      <div class="single-client-det" :style="containerHeight" id="single-client-det">
        <group class="crm-form-group">
          <x-input :class="{'weui-cell_warn': errors.parent_name }"  title="家长姓名" v-model="client.parent_name" placeholder="请输入家长姓名" novalidate :icon-type="iconType" :show-clear="false" @on-blur="onBlur" placeholder-align="right">
            <span slot="label"><i class="require-mark">*</i>家长姓名</span>
          </x-input>
          <x-input :class="{'weui-cell_warn': errors.mobile_num }" title="手机号码" v-model="client.mobile_num" placeholder="输入手机号码" novalidate :icon-type="iconType" :show-clear="false" @on-blur="onBlur" placeholder-align="right">
            <span slot="label"><i class="require-mark">*</i>手机号码</span>
          </x-input>
          <cell :class="{'weui-cell_warn': errors.address }" class="address" title="所在地址" v-model="client.address" placeholder="请输入地址" raw-value placeholder-align="right">
            <span slot="title"><i class="require-mark">*</i>所在地址</span>
            <span>{{ client.address }}</span>
          </cell>
          <cell title="选择地址">
            <region-picker ref="addressPicker" v-model="address" :data="regions"></region-picker>
          </cell>
          <cell title="客户来源" v-model="customSource"></cell>
          <cell title="客户二级来源" v-model="client.second_source_name"></cell>
          <cell title="渠道" v-model="channel_info"></cell>
          <!-- <selector v-if="loginUser.is_team_manager" :class="{'weui-cell_warn': errors.source_id }" direction="rtl" title="客户来源" placeholder="请选择客户来源" :options="clientSourceOptions" v-model="client.source_id" placeholder-align="right" >
            <span slot="label"><i class="require-mark">*</i>客户来源</span>
          </selector> -->
          <cell direction="rtl" title="跟进状态" placeholder="请选择跟进状态" :options="customStatusOptions" :value="client.custom_status | clueType" placeholder-align="right" ></cell>
          <selector :class="{'weui-cell_warn': errors.custom_property }" :readonly="true" v-if="client.is_member === 1" direction="rtl" title="客户属性" placeholder="请选择客户属性" :options="chenJiaoProperty" v-model="client.custom_property" placeholder-align="right" ></selector>
          <selector :class="{'weui-cell_warn': errors.custom_property }"  v-else direction="rtl" title="客户属性" placeholder="请选择客户属性" :options="customPropertyOptions" v-model="client.custom_property" placeholder-align="right" ></selector>
          <!-- <x-input :class="{'weui-cell_warn': errors.address }" title="详细地址" placeholder="请输入详细地址" v-model="client.address" placeholder-align="right"></x-input> -->
          <x-input
         v-model="client.qq_num"
        placeholder="请输入QQ号" novalidate
         @on-blur="onBlur" placeholder-align="right">
          <span slot="label">QQ号</span>
        </x-input>
        <x-input
         v-model="client.wechat_num"
        placeholder="请输入微信号" novalidate
         @on-blur="onBlur" placeholder-align="right">
          <span slot="label">微信号</span>
          </x-input>
        <x-input
         v-model="client.remark"
        placeholder="请输入备注" novalidate
         @on-blur="onBlur" placeholder-align="right">
          <span slot="label">备注</span>
          </x-input>
          <x-input title="创建人" placeholder="输入创建人" novalidate :icon-type="iconType" v-model="client.creator" :show-clear="false" @on-blur="onBlur" placeholder-align="right"></x-input>
        </group>

        <div class="weui-cells-no-margin" v-for="(baby, index) in this.babies" :key="index">
          <div class="weui-cells__title"  slot="after-title">
            宝宝: {{ baby.baby_name }}
            <span class="delete-baby" @click="deleteBaby(baby, index)">删除</span>
          </div>
          <group >
            <x-input :class="{'weui-cell_warn': typeof errors.babies[index] !== 'undefined' && errors.babies[index].baby_name }"  title="宝宝姓名" v-model="baby.baby_name" placeholder="输入宝宝姓名" placeholder-align="right"  :show-clear="false" @on-blur="onBlur" ></x-input>
            <selector :class="{'weui-cell_warn': typeof errors.babies[index] !== 'undefined' && errors.babies[index].baby_sex }" name="experience_time" direction="rtl" title="宝宝性别" v-model="baby.baby_sex" placeholder="输入宝宝性别"  :options="babyGenderOptions" placeholder-align="right"></selector>
            <cell title="出生日期">
              <datetime 
                :start-date="startDate" 
                :end-date="endDate" 
                confirmText="完成" 
                cancelText="取消" 
                title="宝宝生日" 
                v-model="baby.baby_birthday" 
                @change="changeBirthday(baby)" 
                placeholder="请选择宝宝生日" 
                placeholder-align="left">
              </datetime>
            </cell>
          </group>
        </div>


      <edit-family 
        :values="client.family"
        @on-change="onFamilyChange"
        ref="editFamily"></edit-family>

        <div class="btn-group center-btn-group">
          <span class="btn scrm-default-btn add-new-btn pull-left" @click="addBaby">+新增宝宝</span>
          <span class="btn scrm-default-btn save-btn pull-right" @click="saveClientInfo">保存</span>
        </div>

      </div>

      <x-dialog v-model="this.$store.state.app.dialogShow" >
        <div class="dialog-message">
          {{ this.$store.state.app.dialogMessage }}
        </div>
        <span class="vux-close" @click="hideDialog">知道了</span>
      </x-dialog>
    </div>
</template>

<script>
var dateFormat = require('dateformat')
  // import Vue from 'vue'
  // import clientMenu from '../components/client-menu'
  import {showDialog, hideDialog} from '../lib/dialog'
  import {cleanClient} from '../lib/client'
  // import {XInput, XDialog, Group, ChinaAddressData, XAddress, Selector, Datetime} from 'vux'

  import XInput from 'vux/src/components/x-input'
  import Group from 'vux/src/components/group'
  import XAddress from 'vux/src/components/x-address'
  import ChinaAddressData from 'vux/src/datas/china_address.json'
  import Selector from 'vux/src/components/selector'
  import Datetime from 'vux/src/components/datetime'
  import XDialog from 'vux/src/components/x-dialog'
  import Cell from 'vux/src/components/cell'
  import RegionPicker from 'region-picker'
  import data from 'region-picker/src/components/data.json'

  import EditFamily from '../components/edit-family';

  import { DatePicker } from 'element-ui'

  import store from '../store'
  // import VeeValidate from 'vee-validate'
  import { validateClient } from '../lib/validate-rules'

  import {mapActions, mapState} from 'vuex'

  export default{
    data () {
      var d = new Date()
      var month = d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
      var day = d.getDate() < 10 ? '0' + (d.getDate()) : d.getDate()
      var str = d.getFullYear() + '-' + month + '-' + day

      return {
        containerHeight : 'min-height:'+document.body.scrollHeight+'px;',
        id: '',
        endDate: str,
        regions: data,
        startDate: '1990-01-01',
        customSource: '',
        channel_info: '',
        babyBirthday: '',
        isChenJiao:false,
        client: {
          name: '',
          parent_name: '',
          phone: '',
          address: '',
          babyGenderValue:'',
          birthday: '',
          iconType: '',
          source_id: '',
          baby_name: '',
          parent_industry: '',
          babyGenderValue: '',
          address: '',
          // custom_status: '',
          custom_property: '',
          creator: '',
          desc: ''
        },
        baby: {
          baby_sex: 'MALE###',
          baby_name: '',
          baby_birthday : new Date().toLocaleDateString()
        },
        errors: {
          babies: {}
        },
        babies:[],
        iconType: '',
        addressData : ChinaAddressData,

        address: null,

        // source_id: '',
        // parent_industry: '',
        // babyGenderValue: '',

        babyGenderOptions: [
          {
            key : 'MALE###',
            value: '男'
          },
          {
            key: 'FEMALE#',
            value: '女'
          }
        ],

        industryOptions : [
          {
            key: 'IT',
            value:'IT软件业'
          },

          {
            key: 'hairdressing',
            value: '美容美甲'
          }
        ],
        clientSourceOptions: [],
        clientChannelOptions: [],
        followStatus : [

          {
            key: 'followed',
            value:'已跟进'
          },

          {
            key:'unfollowed',
            value:'未跟进'
          }
        ],

        followProperties : [

          {
            key: 0,
            value:'意向客户'
          },

          {
            key:1,
            value:'我的客户'
          }
        ],
        chenJiaoProperty : [
          {
            key: 'YB%23',
            value: '一般客户'
          },
          {
            key: 'YX%23',
            value: '意向客户'
          },
          {
            key: 'YCJ',
            value: '成交客户'
          },
          {
            key: 'WX%23',
            value: '无意向客户'
          },
          {
            key: 'NA%23',
            value: '无效客户'
          },
          {
            key: 'QT%23',
            value: '其它客户'
          }
        ]
      }
    },
    components: {
      'datetime': DatePicker,
      XInput,
      Group,
      ChinaAddressData,
      XAddress,
      Selector,
      // Datetime,
      [RegionPicker.name]: RegionPicker,
      XDialog,
      Cell,
      EditFamily
    },
    methods: {
      changeBirthday (baby) {
        baby.baby_birthday = dateFormat(baby.baby_birthday, 'yyyy-mm-dd')
        console.log(baby, 'changeBirthday', this.endDate, baby.baby_birthday)
        if (this.endDate && this.endDate < baby.baby_birthday) {
          showDialog('出生日期必须不能超过今天')
          baby.baby_birthday = ''
          this.babyBirthday = ''
          return
        }
      },
      refresh (iscroll) {
        console.log('refresh')
        // Refresh current data
      },
      hideDialog: hideDialog,
      log () {
        console.log('ee');
      },

      load (iscroll) {
        console.log('load')
        // Load new data
      },

      test () {
        console.log('test')
      },

      deleteBaby (baby, index) {
        if(this.babies.length>1) {
          this.babies.splice(index, 1)
        } else {
          console.log(this.custom_type, 'ssss')
          if(this.custom_type === 1) {
            showDialog('必须保留一个宝宝喔!');
            setTimeout(() => {   hideDialog() },3300)
          } else {
            this.babies = []
          }
        }
      },

      validate () {
        if(this.custom_type === 0 && this.babies.length === 0) {
          this.errors.babies = []
        }
        return this.$el.getElementsByClassName('weui-cell_warn').length === 0
      },

      onBlur () {
      },
      addBaby () {
        let newBaby = Object.assign({}, this.baby)
        this.babies.push(newBaby);
      },
      onShow () {
        console.log(arguments)
      },
      //初始化客户信息
      initClientInfo (id) {
        let that = this;
        store.dispatch('getCustomInfoById', id)
          .then((response) => {
            if(response.data.errcode === 0) {
              let client = response.data.results;
              that.client = client
              that.initAddress();
              that.client.custom_type = that.custom_type == 1 ? 'QT#' : 'WX#';
              that.client.operator_id = that.loginUser.id
              that.client.operator_name = that.loginUser.name
              that.client.creator = that.loginUser.name
              this.customSource = this.customSources[this.client.source_id]
              this.channel_info = this.channel[this.client.channel_id]
              that.client.custom_property = encodeURIComponent(client.custom_property)
            } else {
              console.debug('系统服务异常！请联系管理员!', JSON.stringify(response.data));
            }
          }).catch(function(error){
            console.log(error)
          })
      },

      initAddress () {
        this.getDefaultAddress({team_id: this.defaultTeamId})
          .then((response) => {
            if (response.data.errcode === 0) {
              if (!this.client.address) {

                this.client.address = response.data.results.address
              }
            }
          }).catch((e) => {
            console.log(e)
        })
        // this.client.address = [this.client.province, this.client.city, this.client.district].join('');
      },

      initBabyInfo (id) {
        let that = this;
        let query = this.$route.query
        store.dispatch('getBabys', id)
          .then((response) => {
            if(response.data.errcode == 0) {
              that.babies = response.data.results;
              that.custom_type = query.custom_type;
              if(this.babies.length === 0)  {
                this.addBaby()
              }
            } else {
              console.log('服务器错误！请联系管理员!');
            }
          })
      },

      submit () {
        let id = this.id;
        let that = this;
        let isValid = this.validate()
        
        const editFamilyValidator = this.$refs.editFamily.$v
        editFamilyValidator.members.$touch()

        if (editFamilyValidator.$error === true) {
          return ;
        }
        
        if(isValid === false) {
          showDialog('保存信息有误，请查看文字标红部分!')
          return ;
        }

        if(this.saveLock) {
          showDialog('提交中....');
          setTimeout(() => {
            hideDialog()
          },300)
          return ;
        }

        this.saveLock = true
        console.debug('that.client', JSON.stringify(that.client))
        console.debug('that.babies', JSON.stringify(that.babies))

        that.client.babys = that.babies
        store.dispatch('saveClientInfo', cleanClient(that.client)).then(function(aresponse){
          if(aresponse.data.errcode == 0) {
            // let params = {info:that.babies, id : id}
            // store.dispatch('saveBabys', params).then(function(response){
            //   if(response.data.errcode == 0) {
            //     console.debug('保存成功！');
            //     showDialog('保存成功!')
            //
            //     setTimeout(() => {
            //       hideDialog();
            //       that.$router.back()
            //     }, 2000)
            //
            //   } else {
            //     console.log('保存宝宝信息失败!', JSON.stringify(response.data))
            //     showDialog(response.data.errmsg);
            //   }
            // }).catch((error) =>{
            //   that.saveLock = false
            //   console.log(error)
            // });
            console.debug('保存成功！');
            showDialog('保存成功!')

            setTimeout(() => {
              hideDialog();
              that.$router.back()
            }, 2000)
          } else {
            showDialog(aresponse.data.errmsg)
            console.log('保存客户信息失败!', JSON.stringify(aresponse.data))
          }

          that.saveLock = false

        }).catch((error) =>{
          console.log(error)
          that.saveLock = false
        });
      },

      onFamilyChange (families) {
        this.client.family = families
      },

      saveClientInfo () {
        this.errors = validateClient(this.client, this.babies)

        setTimeout(() => {
          this.submit()
        })
      },
      ...mapActions({
        getDefaultAddress: 'getDefaultAddress'
      }),

    },

    beforeMount () {
      store.dispatch('getCustomSource')
      store.dispatch('getChannel')
    },

    mounted () {
      let query =  this.$route.query;
      let id = query.id;
      let defaultTeam = Object.keys(this.loginUser.my_team_list)
      this.defaultTeamId = defaultTeam.length ? defaultTeam[0] : ''
      this.id = id;
      this.isChenJiao = query.isChenJiao
      this.initClientInfo(id);
      this.initBabyInfo(id);

    },

    computed : {
      //包含客户详情的列表
      clientsDetail () {
        return this.$store.state.app.clientsDetail;
      },

      //跟进状态选项列表
      customStatusOptions() {
        return this.$store.state.app.customStatusOptions;
      },

      //客户属性选项列表
      customPropertyOptions() {
        return this.$store.state.app.customPropertyOptions;
      },

      loginUser () {
        return this.$store.state.app.user;
      },

      customSources () {
        return this.$store.state.app.customSources;
      },
      ...mapState({
        channel: state => state.app.channel
      })

    },

    watch:{
      customSources () {
        let customSources = this.customSources
        for (let id in customSources) {
          let source = customSources[id]
          this.clientSourceOptions.push({
            key: id,
            value: source
          })
        }
      },
      channel () {
        let channel_list = this.channel
        for (let id in channel_list) {
          let info = channel_list[id]
          this.clientChannelOptions.push({
            key: id,
            value: info
          })
        }
      },
      address (value) {
        const regionPickerElem = this.$refs.addressPicker.$el
        const addressText = this.$refs.addressPicker.$children[0].selected.fullName.replace(/\s/g, '')
        const addressArr = addressText.split('/')
        if (!addressArr) {
          return showDialog('请选择地址！')
        }

        if (addressArr.length < 3) {
          showDialog('请选择区域！')
          addressArr[2] = ''
        }
        if (addressArr.length < 2) {
          return showDialog('请选择市区！')
        }
        this.client.province = addressArr[0]
        this.client.city = addressArr[1]
        this.client.district = addressArr[2]
        this.client.address = addressArr.join('')
      }
    }

  }
</script>

<style lang='less'>
  @import "../less/index.less";

  .single-client-det {
    padding-bottom: 20px;

    .crm-form-group {
      &>.weui-cells {
        overflow: initial;
      }

      .region-picker .picker-menu {
        right: 0px;
      }
    }

    .no-margin {
       &>*{
       margin: 0
       }
    }

    .add-new-btn{
      width: 60%;
    }

    .btn-group{
      &:extend(.clearfix all);
      margin-top: 15px;

      &>*{
        width: 38%;
        text-align: center;
        border-radius: 4px;
        padding: 10px;
        margin: 0 8px;
      }

      .babayArea {
        &:extend(.clearfix all);
        border-top: 1px solid #ccc;
      }

      .pull-left{
        float: left;
      }

      .pull-right{
        float: right;
      }
    }

    .delete-baby {
      float: right;
      color: #39ADFF;
    }

  }
</style>
